﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TruckWatch.Cloud.BusinessLogic;
using TruckWatch.Cloud.Models.EF;
using TruckWatch.Cloud.Models;

namespace Mvc30WebRole1.Controllers
{
    /// <summary>
    /// ServiceController (Message functions)
    /// </summary>
    public partial class ServicesController : Controller
    {
       
        #region Messages

        public ActionResult UpdateDriverAck(string recipientUserId, int ackNumber)
        {
            MessageBL.UpdateClientAck(recipientUserId, ackNumber);

            ViewBag.UserId = recipientUserId;
            ViewBag.Ack = ackNumber;
            return View();
        }

        public JsonResult GetAllMessagesSinceAck(string userId)
        {
            List<Message> messages = MessageBL.GetAllMessagesSinceAck(userId);
            List<TruckWatch.Cloud.Models.MessageModel> messageModels = MessageBL.ConvertMessageToMessageModel(messages);
            return Json(messageModels, JsonRequestBehavior.AllowGet);
        }
        
        public JsonResult GetAllMessages(string userId)
        {
            List<Message> messages = MessageBL.GetAllMessagesForUserId(userId);
            List<MessageModel> messageModels = MessageBL.ConvertMessageToMessageModel(messages);

            return Json(messageModels, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult SendMessage(string recipientUserId, string senderUserId, string messageText, string messageType, string parentMessageId)
        {
            Message message = new Message();
            var recipientDriver = DriverBLEF.GetDriverByUserId(recipientUserId,null,true);
            var senderDriver = DriverBLEF.GetDriverByUserId(senderUserId, null, true);

            message.RecipientDriverId = recipientDriver.Id;
            message.SenderDriverId = senderDriver.Id;
            message.MessageText = messageText;
            message.MessageType = messageType;
            message.SenderIp = Request.UserHostAddress;
            int parentMessageIdint ;
            int.TryParse(parentMessageId, out parentMessageIdint);
            message.ParentMessageId = parentMessageIdint == 0 ? (int?)null : parentMessageIdint;

            MessageBL.AddMessage(message);

            ViewBag.Message = "successfully send message";

            return View(message);
        }

        #endregion

    }
}
